#include "active_event.h"
#include <unistd.h>
#include <string.h>
#include "log.h"
#include "CCReactor.h"


std::unique_ptr<CActiveEvent> CActiveEvent::Attach(CCReactor* cc)
{
	std::unique_ptr<CActiveEvent> p_active_event = NULL;
	CActiveEvent * obj = NULL;
	do
	{
		if (cc == NULL)
		{
			log_error("cc is null");
			break;
		}

		CActiveEvent * obj = new CActiveEvent();
		if(obj == NULL){
			log_error("cc is null");
			break;
		}

		int ret = obj->create();
		if (0 != ret)
		{
			log_error("create CActiveEvent fail");
			break;
		}

		if (cc->AttachPoller(obj) < 0)
		{
			log_error("attach poller fail");
			break;
		}

		p_active_event.reset(obj);
	} while(false);

	if (p_active_event == NULL && obj != NULL)
	{
		delete obj;
	}
	return p_active_event;
}

CActiveEvent::CActiveEvent() : CPollerObject()
{

}
CActiveEvent::~CActiveEvent()
{

}

int CActiveEvent::Init()
{
	CPollerObject::EnableInput();
	return 0;
}

int CActiveEvent::create(void)
{
	netfd = eventfd(0, 0);
	if (netfd == -1){
		log_error("netfd == -1");
        if(netfd >= 0){
            close(netfd);
            netfd = -1;
        }
        return -1;
	}
	return 0;
}

int CActiveEvent::signal(std::int64_t value)
{
    int nwrite = write(netfd, &value, sizeof(std::int64_t));
    if(nwrite != sizeof(std::int64_t)){
        log_error("write failed netfd=%d", netfd);
        return -1;
    }
    return 0;
}
int CActiveEvent::InputNotify(void)
{
    std::int64_t value = 0;
    read(netfd, &value, sizeof(std::int64_t));
    // 执行事件处理
    m_signal_handler(value);
	return 0;
}

int CActiveEvent::HangupNotify(void)
{
	log_error("hangup,fd,%d", netfd);

	return 0;
}